import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../components/Login.vue'
//导入路由组件
import ElementUI from '../components/ElementUI.vue'
import Home from '../components/Home.vue'
import User from '../components/user/user.vue'
import Item from '../components/items/Item.vue'
import Welcome from '../components/Welcome.vue'
import ItemCat from '../components/items/ItemCat.vue'
import addItem from '../components/items/addItem.vue'
import rights from '../components/rights/Rights.vue'
import role from '../components/rights/Role.vue'
import report from '../components/report/Report.vue'
import itemCatParam from '../components/items/ItemCatParam.vue'
//使用路由机制
Vue.use(VueRouter)
const routes = [
  {path: '/', redirect: '/login'},
  {path: '/login', component: Login},
  {path: '/elementUI',component:ElementUI},
  {path: '/home',component: Home,redirect:"/welcome",children: [
     {path: '/user',component: User},
     {path: '/welcome',component: Welcome},
     {path: '/item',component: Item},
     {path: '/itemCat',component: ItemCat},
     {path: '/item/addItem',component: addItem},
     {path: '/rights',component: rights},
     {path: '/role',component: role},
     {path: '/report',component: report},
     {path: '/itemCatParam',component: itemCatParam}
  ]
  }


]
//定义路由对象
const router = new VueRouter({
  routes
})
export default router
// 配置路由导航守卫
//1.to: 将要访问的路径
//2.from: 从哪个路径跳转而来
//3.next: 是一个函数 next() 表示放行 next("/login") 强制跳转
router.beforeEach((to,from,next)=> {
    //1.当用户访问登陆页面,则直接放行 如果不需要执行后续操作 执行return
    //return用于终止程序,如果仅仅是next() 后续行为也会被执行
    if(to.path === '/login') return next()
    console.log("后续行为继续执行")
    //2.当用户访问其他页面  需要检验是否有token
    let token=window.sessionStorage.getItem('token')
    //如果token为null 则访问登录页面
    //if(!token) 与  if(token!=null && token.length>0)相同
    if(!token) return next('/login')
    //不为null
    next()//将所有请求放行
})
